package org.ceteca.explica.client.management;

import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.math.BigDecimal;
import java.net.URL;
import java.rmi.AccessException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.Media;
import javax.print.attribute.standard.OrientationRequested;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRReport;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPrintServiceExporter;
import net.sf.jasperreports.engine.export.JRPrintServiceExporterParameter;
import net.sf.jasperreports.view.JasperViewer;

import org.ceteca.explica.client.ClientContext;
import org.ceteca.explica.client.gui.ExplicaDateSelect;
import org.ceteca.explica.client.gui.ExplicaDetailEntityView;
import org.ceteca.explica.client.gui.ExplicaEvent;
import org.ceteca.explica.client.gui.ExplicaEventListener;
import org.ceteca.explica.client.gui.ExplicaExtensionFieldsView;
import org.ceteca.explica.client.gui.ExplicaGUIBuilder;
import org.ceteca.explica.client.gui.common.CommonClient;
import org.ceteca.explica.core.ExplicaException;
import org.ceteca.explica.core.InterfaceErrors;
import org.ceteca.explica.core.InterfaceExplica;
import org.ceteca.explica.core.common.BaseVO;
import org.ceteca.explica.core.common.CountryOT;
import org.ceteca.explica.core.common.CurrencyOT;
import org.ceteca.explica.core.common.DocumentTotal;
import org.ceteca.explica.core.common.LineaDesgloseIVA;
import org.ceteca.explica.core.common.MultiSelectionSubentityOT;
import org.ceteca.explica.core.common.SelectionSubentityOT;
import org.ceteca.explica.core.management.DocumentLineOT;
import org.ceteca.explica.core.management.DocumentOT;
import org.ceteca.explica.core.management.DocumentTypeOT;
import org.ceteca.explica.core.management.InterfaceManagement;
import org.ceteca.explica.core.management.InterfaceManagementErrors;
import org.ceteca.explica.core.management.ManagementManager;
import org.ceteca.explica.core.management.SerialNumberOT;
import org.ceteca.explica.core.partners.AddressOT;
import org.ceteca.explica.core.partners.InterfacePartners;
import org.ceteca.explica.core.partners.PartnerOT;
import org.ceteca.explica.core.partners.PaymentMethodOT;
import org.ceteca.explica.core.partners.VendorOT;
import org.ceteca.explica.core.util.AddressUtils;
import org.ceteca.explica.core.util.Converter;
import org.ceteca.explica.core.util.OperationResult;
import org.ceteca.explica.core.util.ResultMessage;
import org.ceteca.javaglade.InterfaceGladeGtk;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;

public class DocumentClient extends CommonClient implements
		ExplicaEventListener {

	private Text w_idDocument, w_dateDocument, w_version;
	private Text w_serialNumberPrefix, w_serialNumberValue;
	private Text w_partner, w_documentType, w_vendor;
	private Text w_currency, w_paymentMethod, w_promptPaymentDiscount,
			w_fixedDiscount;
	private Text w_brandName, w_idNumber, w_address_billing,
			w_address_shipping;
	private Text w_postalCode_billing, w_postalCode_shipping, w_city_billing,
			w_cityShipping;
	private Combo w_state_billing, w_state_shipping, w_country_billing,
			w_country_shipping, w_vatRegime;
	private Text w_gross_amount, w_netAmountBT, w_taxesAmount, w_netAmount,
			w_total;
	private Text w_priceList;
	private Composite w_panelLines;
	private ExplicaDateSelect selectDate;
	private Text w_discountAmount, w_prompPaymentAmount;
	private Tree extCatalog, w_treeTaxes;

	private ExplicaDetailEntityView viewLines;
	// private Text w_lastUpdate;

	private Button w_selectDate, w_selectSerialNumber, w_selectVendor,
			w_selectPaymentMethod;
	private Button w_selectCurrency, w_selectPriceList, w_selectPartner;
	private Button w_computeIdNumber;

	/**
	 * 
	 */
	public DocumentClient() {
		super(DocumentOT.class,
				InterfaceManagement.EXPLICA_EDIT_DOCUMENT_GLADE_PATH,
				InterfaceManagement.EXPLICA_EDIT_DOCUMENT_DIALOG_NAME);
	}

	@Override
	public void buildSelectionSets() {
		lSelectionSubentities = new HashSet<SelectionSubentityOT>();

		lSelectionSubentities
				.add(new SelectionSubentityOT(
						InterfaceManagement.EXPLICA_ENTITY_SERIALNUMBER_ID,
						InterfaceManagement.EDIT_DOCUMENT_SERIALNUMBERPREFIX_WIDGETNAME,
						this, w_selectSerialNumber));
		lSelectionSubentities.add(new SelectionSubentityOT(
				InterfacePartners.EXPLICA_ENTITY_PARTNER_ID,
				InterfaceManagement.EDIT_DOCUMENT_PARTNER_WIDGETNAME, this,
				w_selectPartner));
		lSelectionSubentities.add(new SelectionSubentityOT(
				InterfacePartners.EXPLICA_ENTITY_PAYMENTMETHOD_ID,
				InterfaceManagement.EDIT_DOCUMENT_PÀYMENTMETHOD_WIDGETNAME,
				this, w_selectPaymentMethod));
		lSelectionSubentities.add(new SelectionSubentityOT(
				InterfaceExplica.EXPLICA_ENTITY_CURRENCY_ID,
				InterfaceManagement.EDIT_DOCUMENT_CURRENCY_WIDGETNAME, this,
				w_selectCurrency));
		lSelectionSubentities.add(new SelectionSubentityOT(
				InterfaceExplica.EXPLICA_ENTITY_PRICELIST_ID,
				InterfaceManagement.EDIT_DOCUMENT_PRICELIST_WIDGETNAME, this,
				w_selectPriceList));
		lSelectionSubentities.add(new SelectionSubentityOT(
				InterfacePartners.EXPLICA_ENTITY_VENDOR_ID,
				InterfaceManagement.EDIT_DOCUMENT_VENDOR_WIDGETNAME, this,
				w_selectVendor));

		lMultiSelectionSubentities = new HashSet<MultiSelectionSubentityOT>();
		
		lMultiSelectionSubentities.add(new MultiSelectionSubentityOT(
				InterfaceManagement.EXPLICA_ENTITY_DOCUMENT_LINE_ID,
				"treeDocumentLines", this, 
				this.getSwtWidget(InterfaceManagement.EDIT_DOCUMENT_LINES_PANEL_WIDGETNAME), "lines", "document"));

	}

	private void changePartner(PartnerOT partner) {
		this.logger.debug("Changed parther " + partner.getInternalValue());
		if (partner != null) {
			int resultado = ExplicaGUIBuilder
					.getInstance()
					.showConfirmationDialog(
							this.entEditView.getGui().getParentWindow().getShell(),
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.MSG_MANAGEMENT_RELOAD_PARTNER_IN_DOCUMENT),
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.MSG_MANAGEMENT_RELOAD_PARTNER_IN_DOCUMENT_TITLE),
							SWT.ICON_QUESTION, SWT.OK + SWT.CANCEL);
			if (resultado == SWT.CANCEL)
				return;
			w_brandName.setText(partner.getBrandName());
			w_idNumber.setText(partner.getIdNumber());
			w_fixedDiscount.setText(Converter.getInstance().toString(
					partner.getFixedDiscount()));
			w_promptPaymentDiscount.setText(Converter.getInstance().toString(
					partner.getPromptPaymentDiscount()));

			if (partner.getVendor() != null) {
				w_vendor.setData(partner.getVendor());
				w_vendor.setText(partner.getVendor().getName());
			}

			if (partner.getPaymentMethod() != null) {
				w_paymentMethod.setData(partner.getPaymentMethod());
				w_paymentMethod.setText(partner.getPaymentMethod()
						.getDescription());
			}

			if (partner.getCurrency() != null) {
				w_currency.setData(partner.getCurrency());
				w_currency.setText(partner.getCurrency().getDescription());
			}

			if (partner.getPriceList() != null) {
				w_priceList.setData(partner.getPriceList());
				w_priceList.setText(Converter.getInstance().toString(
						partner.getPriceList().getDescription()));
			}

			w_vatRegime.select(partner.getVatRegime());

			if (partner.getBillingAddress() != null
					&& !partner.getBillingAddress().isEmpty())

			{
				AddressOT badd = partner.getBillingAddress().get(0);
				w_address_billing.setText(Converter.getInstance().toString(
						badd.getAddress()));
				w_city_billing.setText(Converter.getInstance().toString(
						badd.getCity()));
				AddressUtils.getInstance().fillCountryCombo(w_country_billing,
						badd.getCountry());
				AddressUtils.getInstance().fillStatesCombo(w_state_billing,
						badd.getCountry(), badd.getState());
				w_postalCode_billing.setText(Converter.getInstance().toString(
						badd.getPostalCode()));
			} else {
				w_address_billing.setText("");
				w_city_billing.setText("");
				w_country_billing.removeAll();
				w_state_billing.removeAll();
				w_postalCode_billing.setText("");
			}

			if (partner.getShippingAddress() != null
					&& !partner.getShippingAddress().isEmpty())

			{
				AddressOT badd = partner.getShippingAddress().get(0);
				w_address_shipping.setText(Converter.getInstance().toString(
						badd.getAddress()));
				w_cityShipping.setText(Converter.getInstance().toString(
						badd.getCity()));
				AddressUtils.getInstance().fillCountryCombo(w_country_shipping,
						badd.getCountry());
				AddressUtils.getInstance().fillStatesCombo(w_state_shipping,
						badd.getCountry(), badd.getState());
				w_postalCode_shipping.setText(Converter.getInstance().toString(
						badd.getPostalCode()));
			} else {
				w_address_shipping.setText("");
				w_cityShipping.setText("");
				w_country_shipping.removeAll();
				w_state_shipping.removeAll();
				w_postalCode_shipping.setText("");
			}

		}
	}

	private void changeSerial(SerialNumberOT serie) {

		w_serialNumberValue.setText(Converter.getInstance().toString(
				serie.getValue()));

		// serie.setValue(serie.getValue()+1);
		DocumentTypeOT tipo = serie.getDocumentType();
		if (tipo != null) {
			w_documentType.setData(tipo);
			w_documentType.setText(Converter.getInstance().toString(
					tipo.getDescription()));

		}

		long num;
		try {
			num = getRemoteManagement().nextSerialNumber(serie);
			w_serialNumberValue.setText(Converter.getInstance().toString(num));
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExplicaException e) {

			e.printStackTrace();

		}

	}

	public void explicaViewModified(ExplicaEvent e) {
		System.out.println("Evento capturado " + e.getEventType());
		if (e.getEventType() == ExplicaEvent.EXPLICA_EVENT_ENTITY_SAVED
				|| e.getEventType() == ExplicaEvent.EXPLICA_EVENT_ENTITY_DELETED)
			this.recalculate();

	}

	@Override
	public BaseVO getEntityData() {
		DocumentOT ent = new DocumentOT();
		if (this.entEditView == null)
			fireExceptionAndExit("Error: null JGlade");
		ent.setAddress_billing(Converter.getInstance().toString(
				w_address_billing.getText()));
		ent.setAddress_shipping(Converter.getInstance().toString(
				w_address_shipping.getText()));
		ent.setBrandName(Converter.getInstance()
				.toString(w_brandName.getText()));
		ent.setCity_billing(Converter.getInstance().toString(
				w_city_billing.getText()));
		ent.setCity_shipping(Converter.getInstance().toString(
				w_cityShipping.getText()));

		ent.setFixedDiscount(Converter.getInstance().parseBigDecimal(
				w_fixedDiscount.getText()));
		// ent.setIdDocument(Converter.getInstance().parseLong(w_idDocument.getText()));
		ent.setIdNumber(Converter.getInstance().toString(w_idNumber.getText()));
		ent.setLastUpdate(new Date());
		ent.setName(Converter.getInstance().toString(w_partner.getText()));
		ent.setPostalCode_billing(Converter.getInstance().toString(
				w_postalCode_billing.getText()));
		ent.setPostalCode_shipping(Converter.getInstance().toString(
				w_postalCode_shipping.getText()));
		ent.setPromptPaymentDiscount(Converter.getInstance().parseBigDecimal(
				w_promptPaymentDiscount.getText()));
		ent.setSerialNumberPrefix(Converter.getInstance().toString(
				w_serialNumberPrefix.getText()));
		ent.setSerialNumberValue(Converter.getInstance().parseLong(
				w_serialNumberValue.getText()));
		ent.setDateDocument(Converter.getInstance().parseDate(
				w_dateDocument.getText()));
		ent.setVatRegime(w_vatRegime.getSelectionIndex());

		ent.setCurrency((CurrencyOT) w_currency.getData());
		ent.setDocumentType((DocumentTypeOT) w_documentType.getData());
		ent.setPartner((PartnerOT) w_partner.getData());
		ent.setVendor((VendorOT) w_vendor.getData());
		ent.setPaymentMethod((PaymentMethodOT) w_paymentMethod.getData());
		ent.setSerial((SerialNumberOT) w_serialNumberPrefix.getData());

		if (ent.getLines() == null)
			ent.setLines(new HashSet<DocumentLineOT>());

		ent.getLines().clear();
		ent.getLines().addAll(viewLines.getRegistries());

		ent.setCountry_billing(AddressUtils.getInstance().getCountryFromCombo(
				w_country_billing));
		ent.setCountry_shipping(AddressUtils.getInstance().getCountryFromCombo(
				w_country_shipping));

		ent.setState_billing(AddressUtils.getInstance().getStateFromCombo(
				w_state_billing));
		ent.setState_shipping(AddressUtils.getInstance().getStateFromCombo(
				w_state_shipping));

		if (selectedEntity != null) {
			ent.setIdDocument(selectedEntity.getInternalId());
			ent.setVersion(((DocumentOT) selectedEntity).getVersion());
		}

		return ent;
	}

	@Override
	public void getWidgets() {

		ArrayList<Integer> codErrors = new ArrayList<Integer>();

		w_idDocument = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_CODE_WIDGETNAME);
		w_address_billing = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_BILLINGADDRESS_WIDGETNAME);
		w_address_shipping = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_SHIPPINGADDRESS_WIDGETNAME);
		w_brandName = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_BRANDNAME_WIDGETNAME);
		w_city_billing = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_BILLINGCITY_WIDGETNAME);
		w_cityShipping = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_SHIPPINGCITY_WIDGETNAME);
		w_currency = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_CURRENCY_WIDGETNAME);
		w_dateDocument = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_DATE_WIDGETNAME);
		w_documentType = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_TYPE_WIDGETNAME);
		w_fixedDiscount = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_FIXEDDISCOUNT_WIDGETNAME);
		w_gross_amount = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_GROSSAMOUNT_WIDGETNAME);
		w_idNumber = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_IDNUMBER_WIDGETNAME);
		// w_name=(Text)getWidget(InterfaceManagement.EDIT_DOCUMENT_NAME_WIDGETNAME);
		// w_netAmount=(Text)getWidget(InterfaceManagement.EDIT_DOCUMENT_NETAMOUNT_WIDGETNAME);
		w_netAmountBT = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_NETAMOUNTBT_WIDGETNAME);
		w_partner = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_PARTNER_WIDGETNAME);
		w_paymentMethod = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_PÀYMENTMETHOD_WIDGETNAME);
		w_postalCode_billing = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_BILLINGPOSTALCODE_WIDGETNAME);
		w_postalCode_shipping = (Text) this.getWidget(
						InterfaceManagement.EDIT_DOCUMENT_SHIPPINGPOSTALCODE_WIDGETNAME);
		w_priceList = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_PRICELIST_WIDGETNAME);
		w_promptPaymentDiscount = (Text) this.getWidget(
						InterfaceManagement.EDIT_DOCUMENT_PROMPTPAYMENTDISCOUNT_WIDGETNAME);
		w_serialNumberPrefix = (Text) this.getWidget(
						InterfaceManagement.EDIT_DOCUMENT_SERIALNUMBERPREFIX_WIDGETNAME);
		w_serialNumberValue = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_SERIALNUMBERVALUE_WIDGETNAME);
		w_taxesAmount = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_TAXESAMOUNT_WIDGETNAME);
		w_total = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_TOTAL_WIDGETNAME);
		w_vendor = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_VENDOR_WIDGETNAME);
		w_version = (Text) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_VERSION_WIDGETNAME);

		w_country_billing = (Combo) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_BILLINGCOUNTRY_WIDGETNAME);
		w_country_shipping = (Combo) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_SHIPPINGCOUNTRY_WIDGETNAME);
		w_state_shipping = (Combo) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_SHIPPINGSTATE_WIDGETNAME);
		w_state_billing = (Combo) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_BILLINGSTATE_WIDGETNAME);
		w_vatRegime = (Combo) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_VATREGIME_WIDGETNAME);

		w_selectCurrency = (Button) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_SELECT_CURRENCY_WIDGETNAME);
		w_selectDate = (Button) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_SELECT_DATE_WIDGETNAME);
		w_selectSerialNumber = (Button) this.getWidget(
						InterfaceManagement.EDIT_DOCUMENT_SELECT_SERIALNUMBER_WIDGETNAME);
		w_selectPartner = (Button) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_SELECT_PARTNER_WIDGETNAME);
		w_selectPaymentMethod = (Button) this.getWidget(
						InterfaceManagement.EDIT_DOCUMENT_SELECT_PAYMENTSELECT_WIDGETNAME);
		w_selectPriceList = (Button) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_SELECT_PRICELIST_WIDGETNAME);
		w_selectVendor = (Button) getWidget(
				InterfaceManagement.EDIT_DOCUMENT_SELECT_VENDOR_WIDGETNAME);

		w_panelLines = ((Composite) this.getWidget(
				InterfaceManagement.EDIT_DOCUMENT_LINES_PANEL_WIDGETNAME));

		if (this.entEditView != null) { // totavia no ha sido construido el entity
			// edit dialog
			viewLines = this.entEditView
					.getMultiSelectEntityView(InterfaceManagement.EXPLICA_ENTITY_DOCUMENT_LINE_ID);
			// }

			w_computeIdNumber = (Button) getWidget(
					InterfaceManagement.EDIT_DOCUMENT_COMPUTE_ID_WIDGETNAME);
			w_discountAmount = (Text) this.getWidget(
							InterfaceManagement.EDIT_DOCUMENT_DISCOUNT_AMOUNT_WIDGETNAME);
			w_prompPaymentAmount = (Text) this.getWidget(
							InterfaceManagement.EDIT_DOCUMENT_PROMP_PAYMENT_AMOUNT_WIDGETNAME);

			w_treeTaxes = (Tree) getWidget(
					InterfaceManagement.EDIT_DOCUMENT_TREE_TAXES_WIDGETNAME);

			if (w_address_billing == null)
				codErrors.add(45);

			if (w_address_billing == null)
				codErrors.add(1);
			if (w_address_shipping == null)
				codErrors.add(2);
			if (w_brandName == null)
				codErrors.add(3);
			if (w_city_billing == null)
				codErrors.add(4);
			if (w_cityShipping == null)
				codErrors.add(44);
			if (w_country_billing == null)
				codErrors.add(5);
			if (w_country_shipping == null)
				codErrors.add(6);
			if (w_currency == null)
				codErrors.add(7);
			if (w_dateDocument == null)
				codErrors.add(8);
			if (w_documentType == null)
				codErrors.add(9);
			if (w_fixedDiscount == null)
				codErrors.add(10);
			if (w_gross_amount == null)
				codErrors.add(11);
			if (w_idDocument == null)
				codErrors.add(12);
			if (w_idNumber == null)
				codErrors.add(13);
			// if (w_netAmount==null)
			// codErrors.add(14);
			if (w_netAmountBT == null)
				codErrors.add(15);
			if (w_partner == null)
				codErrors.add(16);
			if (w_paymentMethod == null)
				codErrors.add(17);
			if (w_postalCode_billing == null)
				codErrors.add(18);
			if (w_postalCode_shipping == null)
				codErrors.add(19);
			if (w_priceList == null)
				codErrors.add(20);
			if (w_promptPaymentDiscount == null)
				codErrors.add(21);
			if (w_selectCurrency == null)
				codErrors.add(22);
			if (w_selectDate == null)
				codErrors.add(23);
			if (w_selectSerialNumber == null)
				codErrors.add(24);
			if (w_selectPartner == null)
				codErrors.add(25);
			if (w_selectPaymentMethod == null)
				codErrors.add(26);
			if (w_selectCurrency == null)
				codErrors.add(27);
			if (w_selectDate == null)
				codErrors.add(28);
			if (w_selectPartner == null)
				codErrors.add(30);
			if (w_selectPaymentMethod == null)
				codErrors.add(31);
			if (w_selectPriceList == null)
				codErrors.add(32);
			if (w_selectVendor == null)
				codErrors.add(33);
			if (w_serialNumberPrefix == null)
				codErrors.add(34);
			if (w_serialNumberValue == null)
				codErrors.add(35);
			if (w_state_billing == null)
				codErrors.add(36);
			if (w_state_shipping == null)
				codErrors.add(37);
			if (w_taxesAmount == null)
				codErrors.add(38);
			if (w_total == null)
				codErrors.add(39);
			if (w_vatRegime == null)
				codErrors.add(40);
			if (w_vendor == null)
				codErrors.add(41);
			if (w_version == null)
				codErrors.add(42);
			if (w_address_billing == null)
				codErrors.add(43);
			if (w_computeIdNumber == null)
				codErrors.add(46);

			extCatalog = (Tree) getWidget(
					InterfaceManagement.EXPLICA_ENTITY_EXTENSION_CATALOG_NAME);

			if (extCatalog == null)
				codErrors.add(47);

			if (w_treeTaxes == null)
				codErrors.add(48);

			if (!codErrors.isEmpty()) {
				logger.debug("Error obteniendo widgets");
				for (Integer i : codErrors)
					logger.debug(i);
				fireExceptionAndExit("Codigo error: " + codErrors);
			}
		}
	}

	@Override
	public void init_specific_components() {

		getWidgets();
		ExplicaGUIBuilder.getInstance().connectSignal(
				InterfaceGladeGtk.GTK_SIGNAL_TYPE_CLICKED, w_selectDate,
				"on_select_date_clicked", this);

		ExplicaGUIBuilder.getInstance().connectSignal(
				InterfaceGladeGtk.GTK_SIGNAL_TYPE_CHANGED, w_country_billing,
				"on_combo_country_billing_changed", this);

		ExplicaGUIBuilder.getInstance().connectSignal(
				InterfaceGladeGtk.GTK_SIGNAL_TYPE_CHANGED, w_country_shipping,
				"on_combo_country_shipping_changed", this);

		ExplicaGUIBuilder.getInstance().connectSignal(
				InterfaceGladeGtk.GTK_SIGNAL_TYPE_CHANGED, w_fixedDiscount,
				"on_document_changed", this);

		ExplicaGUIBuilder.getInstance().connectSignal(
				InterfaceGladeGtk.GTK_SIGNAL_TYPE_CHANGED,
				w_promptPaymentDiscount, "on_document_changed", this);

		ExplicaGUIBuilder.getInstance().connectSignal(
				InterfaceGladeGtk.GTK_SIGNAL_TYPE_CHANGED, w_vatRegime,
				"on_document_changed", this);

		if (viewLines != null) {
			this.logger.debug("Añadiendome como listener");
			viewLines.addExplicaEventListenerAllViews(this);

		}

	}

	public void on_combo_country_billing_changed(Event e) {
		CountryOT newCountry = AddressUtils.getInstance().getCountryFromCombo(
				w_country_billing);
		AddressUtils.getInstance().refillComboStates(w_state_billing,
				newCountry);

	}

	public void on_combo_country_shipping_changed(Event e) {
		CountryOT newCountry = AddressUtils.getInstance().getCountryFromCombo(
				w_country_shipping);
		AddressUtils.getInstance().refillComboStates(w_state_shipping,
				newCountry);
	}

	public void on_date_selected(Event e) {
		w_dateDocument.setText(Converter.getInstance().toString(
				selectDate.getDate()));

	}

	public void on_document_changed(Event e) {
		this.recalculate();
	}

	public void on_select_date_clicked(Event e) {
		selectDate = new ExplicaDateSelect(this.logger, this, "on_date_selected");
		selectDate.build();
		selectDate.show(Converter.getInstance().parseDate(
				w_dateDocument.getText()));

	}

	private void recalculate() {
		DocumentOT doc = (DocumentOT) getEntityData();
		setTotalsWidgetsValues(doc.getTotal());

	}

	@Override
	public void selectSubentity(String parentFieldId, BaseVO subentityOT) {
		if (subentityOT.getEntityId().equals(
				InterfacePartners.EXPLICA_ENTITY_PARTNER_ID)) {
			PartnerOT partner = (PartnerOT) subentityOT;
			changePartner(partner);
		}
		if (subentityOT.getEntityId().equals(
				InterfaceManagement.EXPLICA_ENTITY_SERIALNUMBER_ID)) {
			SerialNumberOT serial = (SerialNumberOT) subentityOT;
			changeSerial(serial);
		}

		super.selectSubentity(parentFieldId, subentityOT);

	}

	@Override
	public void setEditionMode(boolean enabled) {
		getWidgets();
		w_idDocument.setEnabled(false);
		w_documentType.setEnabled(false);
		w_version.setEnabled(false);
		w_gross_amount.setEnabled(false);

		if (w_idDocument.getText().equals("0")
				|| w_idDocument.getText().isEmpty()) {
			w_panelLines.setEnabled(false);
			w_selectSerialNumber.setEnabled(true);
			w_serialNumberValue.setEnabled(true);
		} else {
			w_panelLines.setEnabled(enabled);
			w_selectSerialNumber.setEnabled(false);
			w_serialNumberValue.setEnabled(false);
		}

		w_address_billing.setEnabled(enabled);
		w_address_shipping.setEnabled(enabled);
		w_brandName.setEnabled(enabled);
		w_city_billing.setEnabled(enabled);
		w_cityShipping.setEnabled(enabled);
		w_country_billing.setEnabled(enabled);
		w_country_shipping.setEnabled(enabled);
		w_currency.setEnabled(false);
		w_dateDocument.setEnabled(enabled);
		w_fixedDiscount.setEnabled(enabled);
		w_idNumber.setEnabled(enabled);
		// w_netAmount.setEnabled(false);
		w_netAmountBT.setEnabled(false);
		w_partner.setEnabled(enabled);

		w_paymentMethod.setEnabled(false);

		w_postalCode_billing.setEnabled(enabled);
		w_postalCode_shipping.setEnabled(enabled);
		w_priceList.setEnabled(false);
		w_promptPaymentDiscount.setEnabled(enabled);
		w_selectCurrency.setEnabled(enabled);
		w_selectDate.setEnabled(enabled);
		w_selectPartner.setEnabled(enabled);
		w_selectPaymentMethod.setEnabled(enabled);
		w_selectPriceList.setEnabled(enabled);

		extCatalog.setEnabled(enabled);

		w_selectVendor.setEnabled(enabled);
		w_serialNumberPrefix.setEnabled(false);
		w_state_billing.setEnabled(enabled);
		w_state_shipping.setEnabled(enabled);
		w_taxesAmount.setEnabled(false);
		w_total.setEnabled(false);
		w_vatRegime.setEnabled(enabled);
		w_vendor.setEnabled(false);
		w_discountAmount.setEnabled(false);
		w_prompPaymentAmount.setEnabled(false);
		w_computeIdNumber.setEnabled(enabled);
	}

	private void setTotalsWidgetsValues(DocumentTotal doc) {
		doc.calcular();
		w_gross_amount.setText(Converter.getInstance().toString(
				doc.getSumaImportes()));
		w_discountAmount.setText(Converter.getInstance().toString(
				doc.getImporteDtoComercial()));
		w_prompPaymentAmount.setText(Converter.getInstance().toString(
				doc.getImporteDtoPP()));
		w_netAmountBT.setText(Converter.getInstance().toString(
				doc.getBaseImponible()));
		w_taxesAmount.setText(Converter.getInstance().toString(
				doc.getImporteIva().add( doc.getImporteRE())));
		w_total.setText(Converter.getInstance().toString(doc.getTotal()));
		w_treeTaxes.clearAll(true);
		w_treeTaxes.removeAll();
		w_treeTaxes.setHeaderVisible(true);
		if (w_treeTaxes.getColumnCount() == 0) {
			int columnWidth = 100;
			TreeColumn column = new TreeColumn(w_treeTaxes, SWT.RIGHT);
			column.setText("Base");
			column.setWidth(columnWidth);
			column.setMoveable(false);
			column.setResizable(false);
			column = new TreeColumn(w_treeTaxes, SWT.RIGHT);
			column.setText("%");
			column.setWidth(columnWidth);
			column.setMoveable(false);
			column.setResizable(false);
			column = new TreeColumn(w_treeTaxes, SWT.RIGHT);
			column.setText("Importe");
			column.setWidth(columnWidth);
			column.setMoveable(false);
			column.setResizable(false);
			column = new TreeColumn(w_treeTaxes, SWT.RIGHT);
			column.setText("Total");
			column.setWidth(columnWidth);
			column.setMoveable(false);
			column.setResizable(false);
		}

		TreeItem itResumen = new TreeItem(w_treeTaxes, SWT.NONE);
		itResumen.setText(new String[] {
				Converter.getInstance().toString(doc.getBaseImponible()),
				"-",
				Converter.getInstance().toString(
						doc.getImporteIva().add( doc.getImporteRE())),
				Converter.getInstance().toString(doc.getTotal()) });
		for (LineaDesgloseIVA l : doc.getDesgloseApicable()) {
			TreeItem itResumenBase = new TreeItem(itResumen, SWT.NONE);
			itResumenBase.setText(new String[] {
					Converter.getInstance().toString(l.getBaseImponible()),
					"-",
					Converter.getInstance().toString(
							l.getImporteIva().add( l.getImporteRE())),
					Converter.getInstance().toString(
							l.getBaseImponible().add( l.getImporteIva()).add(
									 l.getImporteRE())) });
			TreeItem itIVA = new TreeItem(itResumenBase, SWT.NONE);
			itIVA.setText(new String[] { "IVA",
					Converter.getInstance().toString(l.getIva()),
					Converter.getInstance().toString(l.getImporteIva()), "-" });
			itIVA.setExpanded(true);
			if (l.getImporteRE().compareTo(new BigDecimal(0)) != 0) {
				TreeItem itRE = new TreeItem(itResumenBase, SWT.NONE);
				itRE
						.setText(new String[] {
								"RE",
								Converter.getInstance().toString(l.getRE()),
								Converter.getInstance().toString(
										l.getImporteRE()), "-" });
				itRE.setExpanded(true);
			}
			itResumen.setExpanded(true);
			itResumenBase.setExpanded(true);

		}
		itResumen.setExpanded(true);

	}

	@Override
	public void setWidgetsValues(BaseVO entity) {
		DocumentOT ent = (DocumentOT) entity;

		w_address_billing.setText(Converter.getInstance().toString(
				ent.getAddress_billing()));
		w_address_shipping.setText(Converter.getInstance().toString(
				ent.getAddress_shipping()));
		w_brandName.setText(Converter.getInstance()
				.toString(ent.getBrandName()));
		w_city_billing.setText(Converter.getInstance().toString(
				ent.getCity_billing()));
		w_cityShipping.setText(Converter.getInstance().toString(
				ent.getCity_shipping()));

		if (ent.getCurrency() != null)
			w_currency.setText(Converter.getInstance().toString(
					ent.getCurrency().getDescription()));
		else
			w_currency.setText("");
		w_currency.setData(ent.getCurrency());

		if (ent.getDocumentType() != null)
			w_documentType.setText(Converter.getInstance().toString(
					ent.getDocumentType().getDescription()));
		else
			w_documentType.setText("");
		w_documentType.setData(ent.getDocumentType());

		w_fixedDiscount.setText(Converter.getInstance().toString(
				ent.getFixedDiscount()));
		w_gross_amount.setText(Converter.getInstance().toString(
				ent.getTotal().getSumaImportes()));
		w_idDocument.setText(Converter.getInstance().toString(
				ent.getIdDocument()));
		w_idNumber.setText(Converter.getInstance().toString(ent.getIdNumber()));

		if (ent.getPartner() != null)
			w_partner.setText(Converter.getInstance().toString(
					ent.getPartner().getName()));
		else
			w_partner.setText("");
		w_partner.setData(ent.getPartner());

		if (ent.getPaymentMethod() != null)
			w_paymentMethod.setText(Converter.getInstance().toString(
					ent.getPaymentMethod().getDescription()));
		else
			w_paymentMethod.setText("");
		w_paymentMethod.setData(ent.getPaymentMethod());

		w_postalCode_billing.setText(Converter.getInstance().toString(
				ent.getPostalCode_billing()));
		w_postalCode_shipping.setText(Converter.getInstance().toString(
				ent.getPostalCode_shipping()));

		w_promptPaymentDiscount.setText(Converter.getInstance().toString(
				ent.getPromptPaymentDiscount()));

		w_serialNumberPrefix.setText(Converter.getInstance().toString(
				ent.getSerialNumberPrefix()));
		w_serialNumberValue.setText(Converter.getInstance().toString(
				ent.getSerialNumberValue()));

		if (ent.getSerial() != null)
			w_serialNumberPrefix.setData(ent.getSerial());

		w_vatRegime.select(ent.getVatRegime());

		if (ent.getVendor() != null)
			w_vendor.setText(Converter.getInstance().toString(
					ent.getVendor().getName()));
		else
			w_vendor.setText("");

		w_vendor.setData(ent.getVendor());

		if (extFieldsView != null)
			extFieldsView.clear();

		if (ent.getDocumentType() != null)
			if (ent.getDocumentType().getExtTable() != null) {
				extFieldsView.setExtTable(ent.getDocumentType().getExtTable());
				fillEntityExtensionTable(ent.getIdDocument());

			}

		this.setTotalsWidgetsValues(ent.getTotal());

		if (viewLines != null)
			viewLines.setRegistries(ent.getLines());

		w_dateDocument.setText(Converter.getInstance().toString(
				ent.getDateDocument()));
		w_version.setText(Converter.getInstance().toString(ent.getVersion()));

		AddressUtils.getInstance().fillCountryCombo(w_country_billing,
				ent.getCountry_billing());
		AddressUtils.getInstance().fillCountryCombo(w_country_shipping,
				ent.getCountry_shipping());
		AddressUtils.getInstance().fillStatesCombo(w_state_billing,
				ent.getCountry_billing(), ent.getState_billing());
		AddressUtils.getInstance().fillStatesCombo(w_state_shipping,
				ent.getCountry_shipping(), ent.getState_shipping());

	}

	@Override
	public OperationResult validateEntity() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void build_extension_fields_view() {
		this.extFieldsView = new ExplicaExtensionFieldsView(this.entEditView.getGui());
		extFieldsView.setExtCatalog(extCatalog);
		extFieldsView.setLogger(logger);
		extFieldsView.setEntityLauncher(this);

	}
	

	@Override
	public OperationResult printEntity() {

		OperationResult result = new OperationResult();
		DocumentOT document = (DocumentOT) selectedEntity;
		if (document == null)
			return result;
		
		Boolean preview=true;
		//SELECT PRINTER
		String printerName=null;
		if (document.getDocumentType() != null) {
			printerName = document.getDocumentType().getPrinterName();
			preview=document.getDocumentType().getPreview();
		}
		PrintService[] services = PrintServiceLookup.lookupPrintServices(null,
				null);
		PrintService selectedService=null;
		for (PrintService i : services) 
			if (i.getName().equals(printerName))
				selectedService = i;
		if (selectedService==null)
			return result;
		
		
		
		
		
		//set company parameters
			HashMap<String, Object> parameters = new HashMap<String, Object>();
			parameters
					.put(
							"COMPANY_NAME",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_NAME));
			parameters
					.put(
							"COMPANY_ADDRESS",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_ADDRESS));
			parameters
					.put(
							"COMPANY_CITY",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_CITY));
			parameters
					.put(
							"COMPANY_COUNTRY",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_COUNTRY));
			parameters
					.put(
							"COMPANY_ZIPCODE",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_ZIP_CODE));
			parameters
					.put(
							"COMPANY_TELEPHONE",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_TELEPHONE));
			parameters
					.put(
							"COMPANY_FAX",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_FAX));
			parameters
					.put(
							"COMPANY_EMAIL",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_EMAIL));
			parameters
					.put(
							"COMPANY_WEB",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_WEB));
			parameters
					.put(
							"COMPANY_CIF",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_CIF));
			parameters
					.put(
							"COMPANY_DISCLAIMER",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_DISCLAIMER));
			parameters
					.put(
							"COMPANY_STATE",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_STATE));


			
			
			//SET REPORT NAME
			String reportPath = InterfaceManagement.EXPLICA_MANAGEMENT_GENERIC_DOCUMENT;
			if (document.getDocumentType() != null) {
				reportPath = document.getDocumentType().getReportName();
			}
			URL url = this.getClass().getResource(reportPath);
			if (url == null) {
				ArrayList<String> lParams = new ArrayList<String>();
				lParams.add(reportPath);
				result
						.addResultMessage(
								OperationResult.RESULT_ERROR,
								ClientContext
										.getInstance()
										.getMsgCatalog()
										.newResultMessage(
												InterfaceErrors.ERR_JASPER_FILE_NOT_FOUND,
												lParams));
				return result;
			}
			

			
			
			//CREATE COLLECTION OF BEANS TO BUILD THE REPORT
			ArrayList<DocumentOT> list = new ArrayList<DocumentOT>();
			DocumentOT doc = (DocumentOT) selectedEntity;
			if (doc != null)
				doc.getTotal().calcular();
			list.add(doc);
			
			try {
				

				JasperPrint jp = JasperFillManager.fillReport(this.getClass()
						.getResourceAsStream(reportPath), parameters,
						new JRBeanCollectionDataSource(list));
				
				
				
	
				
				//SELECT PRINTER
				PrinterJob job = PrinterJob.getPrinterJob();
				job.setPrintService(selectedService);
				
				Media med[] = (Media[])selectedService.getSupportedAttributeValues(Media.class, null, null);

				for (int k=0; k<med.length; k++) {

				System.out.println("Name : " + med[k].getClass());

				}
				
				PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
				
				
				

				
				
				
				
				
				//SET ORIENTATION
				byte orientationReport = jp.getOrientation();
				OrientationRequested orientation = OrientationRequested.PORTRAIT;
				if(orientationReport == JRReport.ORIENTATION_LANDSCAPE)
				orientation = OrientationRequested.LANDSCAPE; 
				printRequestAttributeSet.add(orientation);
				
				
				
				
				//SET NUM COPIES
				int numCopies=1;
				if (document.getPartner()!=null)
					numCopies=document.getPartner().getNumCopies();
				if (numCopies<1)
					numCopies=1;
				printRequestAttributeSet.add(new Copies(numCopies));
				
				
				
				
				
				JRPrintServiceExporter exporter;
				exporter = new JRPrintServiceExporter();
				exporter.setParameter(JRExporterParameter.JASPER_PRINT, jp);
				exporter.setParameter(
						JRPrintServiceExporterParameter.PRINT_SERVICE,selectedService);
				exporter
						.setParameter(
								JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET,
								selectedService.getAttributes());
				exporter
						.setParameter(
								JRPrintServiceExporterParameter.PRINT_REQUEST_ATTRIBUTE_SET,
								printRequestAttributeSet);
				exporter.setParameter(
						JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG,
						Boolean.FALSE);
				exporter.setParameter(
						JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG,
						Boolean.TRUE);
				if (!preview)
					exporter.exportReport();
				else
					JasperViewer.viewReport(jp,false);			
			
				
				
			
				
				
				
				result.addResultMessage(OperationResult.RESULT_OK,
						new ResultMessage(InterfaceErrors.MSG_REPORT_OK));
			} catch (JRException e) {
				result
						.addResultMessage(
								OperationResult.RESULT_ERROR,
								ClientContext
										.getInstance()
										.getMsgCatalog()
										.newResultMessage(
												InterfaceErrors.ERR_JASPERREPORTS_EXCEPTION,
												e));
				e.printStackTrace();
			} catch (PrinterException e) {
				result
				.addResultMessage(
						OperationResult.RESULT_ERROR,
						ClientContext
								.getInstance()
								.getMsgCatalog()
								.newResultMessage(
										InterfaceErrors.ERR_JASPERREPORTS_EXCEPTION,
										e));
				e.printStackTrace();
			}

			return result;

		
	}
	

	
	
	/*

	@Override
	public OperationResult printEntity() {

		OperationResult result = new OperationResult();
		String reportPath = InterfaceManagement.EXPLICA_MANAGEMENT_GENERIC_DOCUMENT;
		String printerName=null;
		int numCopies=1;
		DocumentOT document = (DocumentOT) selectedEntity;
		if (document == null)
			return result;
		if (document.getPartner()!=null)
			numCopies=document.getPartner().getNumCopies();
		if (numCopies<1)
			numCopies=1;
		if (document.getDocumentType() != null) {
			reportPath = document.getDocumentType().getReportName();
			printerName = document.getDocumentType().getPrinterName();
		}

		PrintService[] services = PrintServiceLookup.lookupPrintServices(null,
				null);
		int selectedService = 0;
		
		for (int i = 0; i < services.length; i++) 
			if (services[i].getName().equals(printerName))
				selectedService = i;

			HashMap<String, Object> parameters = new HashMap<String, Object>();
			parameters
					.put(
							"COMPANY_NAME",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_NAME));
			parameters
					.put(
							"COMPANY_ADDRESS",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_ADDRESS));
			parameters
					.put(
							"COMPANY_CITY",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_CITY));
			parameters
					.put(
							"COMPANY_COUNTRY",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_COUNTRY));
			parameters
					.put(
							"COMPANY_ZIPCODE",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_ZIP_CODE));
			parameters
					.put(
							"COMPANY_TELEPHONE",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_TELEPHONE));
			parameters
					.put(
							"COMPANY_FAX",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_FAX));
			parameters
					.put(
							"COMPANY_EMAIL",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_EMAIL));
			parameters
					.put(
							"COMPANY_WEB",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_WEB));
			parameters
					.put(
							"COMPANY_CIF",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_CIF));
			parameters
					.put(
							"COMPANY_DISCLAIMER",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_DISCLAIMER));
			parameters
					.put(
							"COMPANY_STATE",
							ClientContext
									.getInstance()
									.getMsgCatalog()
									.getMessage(
											InterfaceManagementErrors.PARAMETER_MANAGEMENT_COMPANY_STATE));

			// result.add(printEntity(reportPath, parameters));

			URL url = this.getClass().getResource(reportPath);
			if (url == null) {

				ArrayList<String> lParams = new ArrayList<String>();
				lParams.add(reportPath);

				result
						.addResultMessage(
								OperationResult.RESULT_ERROR,
								ClientContext
										.getInstance()
										.getMsgCatalog()
										.newResultMessage(
												InterfaceErrors.ERR_JASPER_FILE_NOT_FOUND,
												lParams));
				return result;
			}
			ArrayList<DocumentOT> list = new ArrayList<DocumentOT>();
			// for (BaseVO b : getRegistries())
			DocumentOT doc = (DocumentOT) selectedEntity;
			if (doc != null)
				doc.getTotal().calcular();

			list.add(doc);
			try {
				JasperPrint jp = JasperFillManager.fillReport(this.getClass()
						.getResourceAsStream(reportPath), parameters,
						new JRBeanCollectionDataSource(list));
				PrinterJob job = PrinterJob.getPrinterJob();
				job.setPrintService(services[selectedService]);
				PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
				MediaSizeName mediaSizeName = MediaSize.findMedia(210, 297,
						MediaPrintableArea.MM);
				printRequestAttributeSet.add(mediaSizeName);
				printRequestAttributeSet.add(new Copies(numCopies));

				JRPrintServiceExporter exporter;

				exporter = new JRPrintServiceExporter();
				exporter.setParameter(JRExporterParameter.JASPER_PRINT, jp);
				exporter.setParameter(
						JRPrintServiceExporterParameter.PRINT_SERVICE,
						services[selectedService]);
				exporter
						.setParameter(
								JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET,
								services[selectedService].getAttributes());
				exporter
						.setParameter(
								JRPrintServiceExporterParameter.PRINT_REQUEST_ATTRIBUTE_SET,
								printRequestAttributeSet);
				exporter.setParameter(
						JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG,
						Boolean.FALSE);
				exporter.setParameter(
						JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG,
						Boolean.TRUE);
				

				exporter.exportReport();
				result.addResultMessage(OperationResult.RESULT_OK,
						new ResultMessage(InterfaceErrors.MSG_REPORT_OK));
			} catch (JRException e) {
				result
						.addResultMessage(
								OperationResult.RESULT_ERROR,
								ClientContext
										.getInstance()
										.getMsgCatalog()
										.newResultMessage(
												InterfaceErrors.ERR_JASPERREPORTS_EXCEPTION,
												e));
				e.printStackTrace();
			} catch (PrinterException e) {
				result
				.addResultMessage(
						OperationResult.RESULT_ERROR,
						ClientContext
								.getInstance()
								.getMsgCatalog()
								.newResultMessage(
										InterfaceErrors.ERR_JASPERREPORTS_EXCEPTION,
										e));
				e.printStackTrace();
			}

			return result;

		
	}
*/
	
	/**
	 * 
	 * Get access to the server via rmi
	 * 
	 * @return ManagementManager. An instance of ManagementManager used to
	 *         invoke operations on the server
	 * @throws ExplicaException
	 */
	protected ManagementManager getRemoteManagement() throws ExplicaException {

		try {

			Registry registry = LocateRegistry
					.getRegistry(InterfaceExplica.RMI_REGISTRY_PORT);

			ManagementManager manager = (ManagementManager) registry
					.lookup(InterfaceManagement.JNDI_MANAGEMENT_MANAGER_EXPORT_NAME);

			return manager;
		} catch (AccessException aEx) {
			aEx.printStackTrace();
			throw new ExplicaException(
					ClientContext
							.getInstance()
							.getMsgCatalog()
							.newResultMessage(
									InterfaceErrors.ERR_RMI_NO_ACCESS,
									aEx,
									(Object) InterfaceManagement.JNDI_MANAGEMENT_MANAGER_EXPORT_NAME,
									(Object) null));
		} catch (NotBoundException nEx) {
			nEx.printStackTrace();
			throw new ExplicaException(
					ClientContext
							.getInstance()
							.getMsgCatalog()
							.newResultMessage(
									InterfaceErrors.ERR_RMI_NOT_BOUND,
									nEx,
									(Object) InterfaceManagement.JNDI_MANAGEMENT_MANAGER_EXPORT_NAME,
									(Object) null));
		} catch (RemoteException rEx) {
			rEx.printStackTrace();
			throw new ExplicaException(
					ClientContext
							.getInstance()
							.getMsgCatalog()
							.newResultMessage(
									InterfaceErrors.ERR_RMI_METHOD_NOT_FOUND,
									rEx,
									(Object) InterfaceManagement.JNDI_MANAGEMENT_MANAGER_EXPORT_NAME,
									(Object) null));
		}
	}

	@Override
	public void fillEntityData() {
		if (this.selectedEntity != null && this.entEditView != null) {
			getWidgets();
			setWidgetsValues((DocumentOT) selectedEntity);
		}
	}
}
